package com.sky.test;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;


public class POITest {
    public static void main(String[] args) {

        write();

        read();
    }


    /**
     * 创建一个excel
     */
    public static void write() {
        //在内存中创建一个Excel文件
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建工作表，指定工作表名称
        XSSFSheet sheet = workbook.createSheet("传智播客");

        //创建行，0表示第一行
        XSSFRow row = sheet.createRow(0);

        //创建单元格，0表示第一个单元格
        row.createCell(0).setCellValue("编号");
        row.createCell(1).setCellValue("名称");
        row.createCell(2).setCellValue("年龄");

        XSSFRow row1 = sheet.createRow(1);
        row1.createCell(0).setCellValue("1");
        row1.createCell(1).setCellValue("小明");
        row1.createCell(2).setCellValue("10");

        XSSFRow row2 = sheet.createRow(2);
        row2.createCell(0).setCellValue("2");
        row2.createCell(1).setCellValue("小王");
        row2.createCell(2).setCellValue("20");

        //通过 输出流 将 workbook对象 下载 到磁盘
        FileOutputStream out = null;
        try {
            out = new FileOutputStream("C:/Users/86158/Desktop/java.xlsx");
            workbook.write(out);

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            try {
                out.flush();
                out.close();
                workbook.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }

    /**
     * 读取一个excel的文件内容    行获取的时候是0开始，列是从1开始，所有一个有等号，一个没等号
     */
    public static void read() {
        XSSFWorkbook book = null;
        try {
            //获取要读取的工作薄对象
            book = new XSSFWorkbook("C:/Users/86158/Desktop/happy.xlsx");

            //得到sheet表格对象
            XSSFSheet sheet = book.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();

            for (int i = 0; i <= lastRowNum; i++) {
                XSSFRow row = sheet.getRow(i);
                short lastCellNum = row.getLastCellNum();     //得到 每一行的最后一列的列数

                for (int j = 0; j < lastCellNum; j++) {

                    String cellValue = row.getCell(j).getStringCellValue();
                    System.out.println(cellValue);
                }
            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                book.close();  //关闭资源
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }


}
